package com.etc.thread;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;

import com.etc.controller.DamageProcess;
import com.etc.controller.LoginController;
import com.etc.controller.SerializeOperation;
import com.etc.entity.Counter;
import com.etc.entity.Role;
import com.etc.service.CounterService;

public class MultiThread implements Runnable {

	Socket sock = null;
	DataInputStream dis = null;
	DataOutputStream dos = null;
	LoginController loginController = new LoginController();
	CounterService counterSer = new CounterService();
	DamageProcess dp = new DamageProcess();
	static ArrayList<Role> onLineRoles = new ArrayList<>();
	static ArrayList<Counter> counters = new ArrayList<>();
	static ArrayList<Role> pkRoom = new ArrayList<>(2);

	public MultiThread(Socket sock) {
		super();
		this.sock = sock;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		String str = null;
		String restr = null;
		while (true) {
			try {
				dis = new DataInputStream(sock.getInputStream()); // 获取数据输入流
				dos = new DataOutputStream(sock.getOutputStream());
				str = dis.readUTF();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 字符串分割
			String[] command = str.split("#");
			switch (command[0]) {
			// 如果是登陆
			case "login":
				restr = loginOperation(command);
				try {
					dos.writeUTF(restr);
					dos.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;
			// 如果注册
			case "register":
				restr = registerOperation(command);
				try {
					dos.writeUTF(restr);
					dos.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;
			//如果是开始决斗
			case "fight":
				fightOperation(command);
				try {
					dos.writeUTF(restr);
					dos.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;
			//如果是添加进在线角色
			case "addOnlineRole":
				addOnlineRoleOperation(command);
				updateOnlineDate();
				restr = "onLineRoles.dat";
				try {
					dos.writeUTF(restr);
					dos.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;
			//判断是否在pk里面
			case "inPKRoom":
				restr = inPKRoomOperation(restr, command);
				try {
					dos.writeUTF(restr);
					dos.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;
			case "useSkill":
				Role enemy = null;
				Role role = null;
				String roleId = command[1];
				int skillIndex = Integer.valueOf(command[2]);
				for(int i = 0; i<pkRoom.size(); i++) {
					if(pkRoom.get(i).getRoleId().equals(roleId)) {
						role = pkRoom.get(i);
						enemy = pkRoom.get(pkRoom.size()-1-i);
					}
				}
				String useSkillMsg = dp.useSkillMsgOnce(role, enemy, skillIndex);
				String startDualOnce = dp.startDualOnce(role, enemy);
				String endRoundMsg = dp.endRound(role, enemy);
				restr = role.getRoleId() + "#"+ useSkillMsg + "#" + startDualOnce + "#" + endRoundMsg;
				Server server = new Server();
				server.sendToAllClients(restr);
				break;
			}
		}
	}

	private String inPKRoomOperation(String restr, String[] command) {
		String enemyId = null;
		String roleId =command[1];
		for (int i=0; i<pkRoom.size(); i++) {
			if(pkRoom.get(i).getRoleId().equals(roleId)) {  //如果在PK房间，
				enemyId = pkRoom.get(pkRoom.size()-i-1).getRoleId(); //另外一个人就是对手
				restr = "startFight#" + enemyId;
			}
		}
		return restr;
	}

	//PK开始的操作
	private void fightOperation(String[] command) {
		String roleId = command[1];
		String enemyId = command[2];
		for (Role role : onLineRoles) {
			if(role.getRoleId().equals(roleId)) {
				pkRoom.add(role);
			}else if(role.getRoleId().equals(enemyId)) {
				pkRoom.add(role);
			}
		}
	}

	//添加一个在线角色
	private void addOnlineRoleOperation(String[] command) {
		String counterId = command[1];
		String roleId = command[2];
		boolean confirm = false;
		for (Counter counter : counters) {
			ArrayList<Role> roles = counter.getRoles();
			for (Role role : roles) {
				if (counter.getId().equals(counterId) && role.getRoleId().equals(roleId)) {
					for(Role r : onLineRoles) {
						if(r.equals(role)) {
							confirm = true;
							break;
						}
					}
					if(confirm == false) {	  //已经存在的不会再次添加					
						onLineRoles.add(role);						
					}
				}
			}
		}
	}

	//更新在线数据
	private void updateOnlineDate() {
		SerializeOperation.saveToFile(onLineRoles, "onLineRoles.dat");
	}

	// 注册操作
	private String registerOperation(String[] command) {
		String restr;
		String userIdReg = command[1];
		String passwordReg = command[2];
		if (loginController.registerConfrim(userIdReg)) {
			restr = "error";
		} else {
			counterSer.addCounter(userIdReg, passwordReg);
			restr = doLogin(userIdReg, passwordReg);
		}
		return restr;
	}

	// 登陆操作
	private String loginOperation(String[] command) {
		String restr;
		String userId = command[1];
		String password = command[2];
		if (loginController.login(userId, password) == null) {
			restr = "error";
		} else {
			restr = doLogin(userId, password);
		}
		return restr;
	}

	private String doLogin(String userId, String password) {
		boolean confirm = false;
		String restr;
		Counter counter = loginController.login(userId, password);
		for(Counter c : counters) {
			if(c.equals(counter)) {
				confirm = true;
				break;
			}
		}
		if(confirm == false) {	  //已经存在的不会再次添加					
			counters.add(counter);
		}
		String fileName = counter.getId() + ".dat";
		SerializeOperation.saveToFile(counter, fileName);
		byte[] bytes = SerializeOperation.getBytes(fileName);
		restr = new String(fileName);
		return restr;
	}

	public void sendMessageToClient(String message) {
		try {
			dos.writeUTF(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

